/*
* $Id: Sort.cpp 117 2010-07-13 09:42:19Z volok-aleksej@yandex.ru $
*
* Copyright 2009 by Volokitin Alexey
* All rights reserved
*
*/
#include "Common/include.h"
#include "Sort.h"
#include "TableCelRow.h"

CSort::CSort(int nColumn){
	m_nColumn = nColumn;
}

int CSort::Compare(CTableCelRow* pRow1, CTableCelRow* pRow2){
	tableHeader::type tp = pRow1->GetTypeColumn(m_nColumn);
	std::tstring strValue1 = pRow1->GetValueColumn(m_nColumn);
	std::tstring strValue2 = pRow2->GetValueColumn(m_nColumn);
	bool bLess = false, bMore = false;
	if(tp == tableHeader::INTEGER){
		int v1 = _ttoi(strValue1.c_str()), v2 = _ttoi(strValue2.c_str());
		bLess = v1 < v2;
		bMore = v1 > v2;
	}else if(tp == tableHeader::DOUBLE){
		double v1 = _tstof(strValue1.c_str()), v2 = _tstof(strValue2.c_str());
		bLess = v1 < v2;
		bMore = v1 > v2;
	}else if(tp == tableHeader::STRING){
		bLess = strValue1 < strValue2;
		bMore = strValue1 > strValue2;
	}else if(tp == tableHeader::DATE){
		time_t v1 = CConvertFunction::ConvertFromDate(strValue1), v2 = CConvertFunction::ConvertFromDate(strValue2);
		bLess = v1 < v2;
		bMore = v1 > v2;
	}else if(tp == tableHeader::BOOL){
		bLess = strValue1 == _T("-") && strValue2 == _T("+");
		bMore = strValue1 == _T("+") && strValue2 == _T("-");
	}
	if(bLess)
		return -1;
	else if(bMore)
		return 1;
	else 
		return 0;
}

void CSort::Swap(CTableCelRow** From, CTableCelRow** To){
	CTableCelRow *pRow = (*From)->m_pNext, *pRow1 = (*To)->m_pBack;
	if(To + 1 == From){
		(*From)->m_pNext = *To;
		(*To)->m_pBack = *From;
	}else{
		(*From)->m_pNext = (*To)->m_pNext;
		if((*From)->m_pNext)
			(*From)->m_pNext->m_pBack = *From;
		(*To)->m_pBack = (*From)->m_pBack;
		if((*To)->m_pBack)
			(*To)->m_pBack->m_pNext = *To;
	}
	if(From + 1 == To){
		(*To)->m_pNext = *From;
		(*From)->m_pBack = *To;
	}else{
		(*To)->m_pNext = pRow;
		if(pRow)
			(*To)->m_pNext->m_pBack = *To;
		(*From)->m_pBack = pRow1;
		if(pRow1)
			(*From)->m_pBack->m_pNext = *From;
	}
	pRow = *From;
	*From = *To;
	*To = pRow;
}

void CSort::Sort(CTableCelRow** s_arr,int first, int last){
	int i = first, j = last;
	CTableCelRow* x = s_arr[(first + last) / 2];
	do {
		while (Compare(s_arr[i], x) < 0) i++;
		while (Compare(s_arr[j], x) > 0) j--;

		if(i <= j) {
			if (i < j) Swap(&s_arr[i], &s_arr[j]);
			i++;
			j--;
		}
	} while (i <= j);

	if (i < last)
		Sort(s_arr, i,last);
	if (first < j)
		Sort(s_arr,first,j);
}
